/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.ing.sisval.gui.seguridad;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import org.ing.sisval.be.BEPersona;
import org.ing.sisval.bl.BLPersona;
import org.ing.sisval.gui.JFPrincipal;

import org.rx.cr.conf.Config;
import org.rx.cr.util.Utilitarios;
import static org.rx.cr.util.Utilitarios.escapeExit;

/**
 *
 * @author Mysham
 */
public class JFAcceso extends javax.swing.JFrame {

    static {
        JFrame.setDefaultLookAndFeelDecorated(true);
        JDialog.setDefaultLookAndFeelDecorated(true);
    }

    /**
     * Creates new form JFAcceso
     */
    private BEPersona beUsuario = null;
    private BLPersona blUsuario = null;

    private Config config;

    public JFAcceso() {
        initComponents();
        Utilitarios.setIconoVentana(this, "/org/ing/sisval/imagen/Dollar.png");
        Utilitarios.centreaVentana(this);
        Utilitarios.adaptarMovimiento(this);
        Utilitarios.adaptarForma(this, 15, 15);
        Utilitarios.addEnterFocusEvent(new Object[][]{{txfUsuario, txfClave}});
        Utilitarios.addEnterDoclickEvent(new Object[][]{{txfClave, jbIniciarSesion}});
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jbIniciarSesion = new javax.swing.JButton();
        jbCancelar = new javax.swing.JButton();
        txfUsuario = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        txfClave = new javax.swing.JPasswordField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setUndecorated(true);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jPanel1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/ing/sisval/imagen/s_usuario_1.png"))); // NOI18N

        jbIniciarSesion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/ing/sisval/imagen/s_iniciar.png"))); // NOI18N
        jbIniciarSesion.setText("Iniciar");
        jbIniciarSesion.setToolTipText("");
        jbIniciarSesion.setBorder(null);
        jbIniciarSesion.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jbIniciarSesion.setMargin(new java.awt.Insets(2, 5, 2, 5));
        jbIniciarSesion.setOpaque(false);
        jbIniciarSesion.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
        jbIniciarSesion.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jbIniciarSesion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbIniciarSesionActionPerformed(evt);
            }
        });
        jbIniciarSesion.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jbIniciarSesionKeyPressed(evt);
            }
        });

        jbCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/ing/sisval/imagen/s_cancelar.png"))); // NOI18N
        jbCancelar.setText("Cancelar");
        jbCancelar.setBorder(null);
        jbCancelar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jbCancelar.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
        jbCancelar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jbCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbCancelarActionPerformed(evt);
            }
        });

        txfUsuario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txfUsuarioActionPerformed(evt);
            }
        });
        txfUsuario.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txfUsuarioKeyPressed(evt);
            }
        });

        jLabel2.setText("USUARIO :");

        jLabel3.setText("CONTRASEÑA :");

        txfClave.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txfClaveKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 280, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(41, 41, 41)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel3)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addGap(22, 22, 22)
                                        .addComponent(jbIniciarSesion)))
                                .addGap(42, 42, 42)
                                .addComponent(jbCancelar))
                            .addComponent(txfUsuario, javax.swing.GroupLayout.DEFAULT_SIZE, 194, Short.MAX_VALUE)
                            .addComponent(txfClave))))
                .addGap(0, 0, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 219, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txfUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txfClave, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jbIniciarSesion)
                    .addComponent(jbCancelar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 2, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txfUsuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txfUsuarioActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txfUsuarioActionPerformed

    private void jbIniciarSesionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbIniciarSesionActionPerformed
        // TODO add your handling code here:
        try {
            validarDatosUsuario();
        } catch (Exception ex) {
            Logger.getLogger(JFAcceso.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("Error al validar en acceso");
        }


    }//GEN-LAST:event_jbIniciarSesionActionPerformed

    private void jbCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbCancelarActionPerformed
        // TODO add your handling code here:
        Utilitarios.salir(this);
    }//GEN-LAST:event_jbCancelarActionPerformed

    private void txfUsuarioKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txfUsuarioKeyPressed
        // TODO add your handling code here:
        escapeExit(evt);
    }//GEN-LAST:event_txfUsuarioKeyPressed

    private void jbIniciarSesionKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jbIniciarSesionKeyPressed
        escapeExit(evt);
    }//GEN-LAST:event_jbIniciarSesionKeyPressed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        // TODO add your handling code here:
        System.exit(0);
    }//GEN-LAST:event_formWindowClosing

    private void txfClaveKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txfClaveKeyPressed
        // TODO add your handling code here:
        escapeExit(evt);
    }//GEN-LAST:event_txfClaveKeyPressed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JButton jbCancelar;
    private javax.swing.JButton jbIniciarSesion;
    private javax.swing.JPasswordField txfClave;
    private javax.swing.JTextField txfUsuario;
    // End of variables declaration//GEN-END:variables

    public Config getConfig() {
        return config;
    }

    public void setConfig(Config config) {
        this.config = config;
    }

    public void validarDatosUsuario() throws Exception {
        blUsuario = new BLPersona(getConfig());
        if (txfUsuario.getText().trim().length() > 0 || txfClave.getText().trim().length() > 0) {
            beUsuario = blUsuario.autenticarUsuario(txfUsuario.getText().trim(), txfClave.getText().trim());
            if (beUsuario != null) {
                if (beUsuario.getEstadocuenta().toLowerCase().equals("activo")) {
                    blUsuario = new BLPersona(getConfig());
                    iniciarSistemaPrincipal();

                } else {
                    txfUsuario.requestFocus();
                    JOptionPane.showMessageDialog(this, "Su cuenta se encuentra inactiva", null, JOptionPane.INFORMATION_MESSAGE);

                }

            } else {
                txfUsuario.requestFocus();
                JOptionPane.showMessageDialog(this, "El usuario no existe, contáctese con el administrador. ", "Autenticacion", JOptionPane.INFORMATION_MESSAGE);

            }

        } else {
            JOptionPane.showMessageDialog(this, "Ingrese todos los datos", "Autenticacion", JOptionPane.INFORMATION_MESSAGE);

        }

    }

    private void iniciarSistemaPrincipal() {
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    JFPrincipal root = new JFPrincipal(getConfig());
                    root.setPersonal_logueado(beUsuario);
                    dispose();
                    txfUsuario.setText("");
                    txfClave.setText("");
                    txfUsuario.requestFocus();
                    root.setVisible(true);
                } catch (Exception ex) {
                    Logger.getLogger(JFAcceso.class.getName()).log(Level.SEVERE, null, ex);
                    System.out.println("No se ha podido iniciar el sistema" + ex);

                }
            }
        });
    }
}
